import 'package:ds18LedBtc/bluetooth/blue_data_model.dart';
import 'package:ds18LedBtc/common/color_list.dart';
import 'package:ds18LedBtc/common/slider.dart';
import 'package:ds18LedBtc/tool/assets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_kit_audio/flutter_kit_audio.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../common/custom_pickerview.dart';

class ColorView extends StatefulWidget {
  int currentType = 0;
  double currentBright = 5;
  double currentSpeed = 16;
  int selectColor = 0xFFEA3324;
  Function(String tag, dynamic value) onChanged;
  ColorView(
      {super.key,
      required this.currentType,
      required this.currentBright,
      required this.currentSpeed,
      required this.selectColor,
      required this.onChanged});

  @override
  State<ColorView> createState() => _ColorViewState();
}

class _ColorViewState extends State<ColorView> {
  late final CircularColorPicker _coloCircular;
  late final CustomPickerview _picker;
  int selectColorIndex1 = 0;
  int selectColorIndex2 = 100;
  List<int> colorList1 = [0xFFEA3324, 0xFF75F94C, 0xFF0021DB, 0xFFFFFC54, 0xFFE77735, 0xFF74FBFB];
  List<int> colorList2 = [0xFFFFFFFF, 0xFF75F94C, 0xFF0021DB, 0xFFFFFC54, 0xFFE77735, 0xFF74FBFB];
  @override
  void initState() {
    super.initState();

    ///色盘呢
    _coloCircular = CircularColorPicker(
      cirulaImage: assets.color,
      pointImage: assets.color_point,
      padding: const EdgeInsets.only(left: 0, right: 0),
      onChange: (p0) {
        // if (widget.color_select_list.isNotEmpty && p0[0] != 0 && p0[1] != 0 && p0[2] != 0) {
        if (selectColorIndex1 != 100 && p0[0] != 0 && p0[1] != 0 && p0[2] != 0) {
          setState(() {
            widget.selectColor = p0.decimal;
            _update();
          });
          widget.onChanged('Color', {'Bright': widget.currentBright.toInt(), 'Color': p0.decimal});
        }
      },
    );

    _picker = CustomPickerview(
        items: [typeList.map(($0) => $0.keys.first).toList()],
        selectIndexs: [getCurrentTypeIndex(widget.currentType)],
        onChanged: (p0, p1) {
          FlutterKitAudio.customSound(soundType: FlutterKitAudioCustomSoundType.click18);
          widget.onChanged('LEDType', typeList[p1].values.first);
        });

    ///监听灯的类型
    GlobalDataNotifier().dataStream.listen((data) {
      if (data is DataModel) {
        if (data.type != widget.currentType) {
          _picker.updateData([getCurrentTypeIndex(data.type)]);
        }
      }
    });
  }

  int getCurrentTypeIndex(int type) {
    return typeList
        .asMap()
        .entries
        .firstWhere(($0) => $0.value.values.first == type, orElse: () => typeList.asMap().entries.first)
        .key;
  }

  @override
  void didUpdateWidget(covariant ColorView oldWidget) {
    super.didUpdateWidget(oldWidget);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _update();
    });
  }

  void _update() {
    if (selectColorIndex2 == 100 && selectColorIndex1 < colorList1.length && widget.selectColor != 0x0) {
      _coloCircular.kstate.setInitialColor(Color(0xFF000000 | widget.selectColor));
      setState(() {
        colorList1[selectColorIndex1] = 0xFF000000 | widget.selectColor;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double appBarHeight = AppBar().preferredSize.height;
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
      return Container(
        color: Colors.transparent,
        width: constraints.maxWidth,
        height: constraints.maxHeight,
        child: Stack(
          children: [
            ///背景LOGO
            Positioned(top: statusBarHeight, right: 60, left: 60, height: 40, child: Image.asset(assets.DS18)),

            ///亮度
            Positioned(
                top: statusBarHeight + 20,
                left: 10,
                width: 30,
                height: constraints.maxHeight / 2.0 - statusBarHeight,
                child: SliderItem(
                    icon1: assets.bright1,
                    icon2: assets.bright2,
                    currentValue: widget.currentBright.toDouble(),
                    min: 1,
                    max: 10,
                    onChanged: (p0) {
                      widget.currentBright = p0;
                      widget.onChanged('Bright', {'Bright': p0.toInt(), 'Color': widget.selectColor});
                    })),

            ///速度
            Positioned(
                top: statusBarHeight + 20,
                right: 10,
                width: 30,
                height: constraints.maxHeight / 2.0 - statusBarHeight,
                child: SliderItem(
                    icon1: assets.speed_add,
                    icon2: assets.speed_sub,
                    currentValue: widget.currentSpeed,
                    min: 1,
                    max: 31,
                    onChanged: (p0) => widget.onChanged('Speed', p0.toInt()))),

            ///
            Positioned(
                top: statusBarHeight + 40,
                left: 80,
                right: 80,
                height: 30,
                child: const Center(child: Text('MODES', style: TextStyle(fontSize: 20, color: Colors.white)))),

            ///循环模式
            Positioned(
              top: statusBarHeight + 70,
              left: 80,
              right: 80,
              height: 80,
              child: Container(
                decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: Color_alert_view),
                child: _picker,
              ),
            ),

            ///圆盘
            Positioned(
                top: constraints.maxHeight / 4.0 + 20,
                left: 50,
                right: 50,
                height: constraints.maxWidth - 100,
                child: Container(
                    decoration: BoxDecoration(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.circular((constraints.maxWidth - 100) / 2.0),
                        border: Border.all(color: Colors.black, width: 10)),
                    child: _coloCircular)),

            ///present颜色
            Positioned(
                left: 30,
                right: 30,
                height: 100,
                bottom: 150,
                child: ColorList(
                  title: 'USER PRESETS',
                  selectIndex: selectColorIndex1,
                  colorList: colorList1,
                  onChanged: (p0, p1) {
                    setState(() {
                      widget.selectColor = p0.decimal;
                      selectColorIndex1 = p1;
                      selectColorIndex2 = 100;
                      _coloCircular.kstate.setInitialColor(Color(p0.decimal));
                    });
                    widget.onChanged('Color', {'Bright': widget.currentBright.toInt(), 'Color': p0.decimal});
                  },
                )),

            ///standard 颜色
            Positioned(
                left: 30,
                right: 30,
                height: 100,
                bottom: 50,
                child: ColorList(
                  title: 'PRESETS',
                  selectIndex: selectColorIndex2,
                  colorList: colorList2,
                  onChanged: (p0, p1) {
                    setState(() {
                      widget.selectColor = p0.decimal;
                      selectColorIndex1 = 100;
                      selectColorIndex2 = p1;
                      _coloCircular.kstate.setInitialColor(Color(p0.decimal));
                    });
                    widget.onChanged('Color', {'Bright': widget.currentBright.toInt(), 'Color': p0.decimal});
                  },
                )),
          ],
        ),
      );
    });
  }
}
